import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/home'

import { GET_TOKEN } from '@/utils/token'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'

nprogress.configure({ showSpinner: false })

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/index' },
  {
    path: '/index',
    name: 'Home',
    meta: {
      title: '首页'
    },
    component: HomeView
  },
  {
    path: '/articlelist',
    name: 'ArticleList',
    meta: {
      title: '文章列表'
    },
    props: (route) => {
      let query = route.query
      return { ...query }
    },
    component: () => import('@/views/article')
  },
  {
    path: '/article/:id',
    name: 'ArticlePage',
    meta: {
      title: '文章详情页'
    },
    props: true,
    component: () => import('@/views/article/ArticlePage'),
    beforeEnter: (to, from, next) => {
      console.log('路由独享的守卫:beforeEnter')
      next()
    }
  },
  {
    path: '/login',
    name: 'Login',
    meta: {
      title: '登录'
    },
    component: () => import('@/views/login')
  },
  {
    path: '/req',
    name: 'Req',
    meta: {
      title: 'axios请求'
    },
    component: () => import('@/views/req')
  },
  {
    path: '*',
    component: () => import('@/views/404')
  }
]

const router = new VueRouter({
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  console.log('全局前置守卫:beforeEach')
  nprogress.start()
  if (to.meta.title) {
    document.title = to.meta.title
  }

  const token = GET_TOKEN()

  handleAuthentication(to, from, next, token)
})

function handleAuthentication(to, from, next, token) {
  if (!token) {
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login' })
      nprogress.done()
    }
  } else {
    if (to.path === '/login') {
      next({ path: '/' })
      nprogress.done()
    } else {
      next()
    }
  }
}

// 全局解析守卫
router.beforeResolve((to, from, next) => {
  console.log('全局解析守卫:beforeResolve')
  next()
})

// 全局后置守卫
router.afterEach(() => {
  console.log('全局后置守卫:afterEach')
  nprogress.done()
})

export default router
